package me.yangxy.learning.controller;

import me.yangxy.learning.api.DirectoryService;
import me.yangxy.learning.api.vo.AddContentReq;
import me.yangxy.learning.api.vo.DirectoryItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/directory")
public class ServiceController {


    @Autowired
    private DirectoryService service;

    /**
     * 批量添加语句记录
     * @param data
     * @return
     */
    @PutMapping("/add")
    public String add(@RequestBody String data){
        List<AddContentReq> contentReqList = parseToContentReq(data);
        service.addContents(contentReqList);
        return "OK";
    }


    /**
     * 随机获取一个结果
     * @return
     */
    @GetMapping("/random")
    @ResponseBody
    public DirectoryItemVO getRandom(){
        List<DirectoryItemVO> allItems = service.queryAllContent();
        int idx = new Random().nextInt(allItems.size());
        return allItems.get(idx);
    }

    private List<AddContentReq> parseToContentReq(String data) {
        String[] entries = data.split("\n");
        int flag = 0;

        List<AddContentReq> list = new ArrayList<>();
        AddContentReq req = new AddContentReq();
        for(int i = 0; i < entries.length; i++){
            String content = entries[i].trim();
            if(StringUtils.isEmpty(content)){
                continue;
            }
            if(flag%2==0){
                req = new AddContentReq();
                req.setEnglishContent(content);
            }else{
                req.setChineseContent(content);
                list.add(req);
            }
            flag++;
        }

        return list;

    }

}
